package com.cz.nongyetongv5.activity;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.cache.CommonUtil;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.custom.dialog.CustomDialog;
import com.cz.nongyetongv5.utils.CharsetUtil;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.DialogUtil;
import com.cz.nongyetongv5.utils.GoHomeUtil;
import com.cz.nongyetongv5.utils.HttpUtils;
import com.cz.nongyetongv5.utils.HttpUtils.OnRequestExecuted;

public class NewsCommentActivity extends Activity {

	private ViewGroup btnBack = null;

	private EditText edtCommend = null;

	private User user;

	private SharedPreferences preferences = null;

	private static final String shared_preferences = "news_comment";

	private Button btnSendComment = null;

	private String newsId = null;

	@Override
	protected void onDestroy() {

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().remove(this);

		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().add(this);

		setContentView(R.layout.newcomment);

		user = (User) getIntent().getSerializableExtra("user");

		newsId = (String) getIntent().getSerializableExtra("id");

		preferences = getSharedPreferences(shared_preferences,
				Context.MODE_PRIVATE);

		btnBack = (ViewGroup) findViewById(R.id.btnBack);

		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});

		btnSendComment = (Button) findViewById(R.id.btnSendComment);

		btnSendComment.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (CommonUtil.checkNetState(NewsCommentActivity.this)) {

					new AsyncTask<Integer, Integer, Integer>() {

						private int responseCodeRet;

						private String responseBodyRet;

						@Override
						protected Integer doInBackground(Integer... params) {

							String json = null;

							String text = edtCommend.getText().toString()
									.trim();

							try {
								JSONObject jsonObject = new JSONObject();

								String postTime = "";

								SimpleDateFormat sdf = new SimpleDateFormat(
										"yyyy-MM-dd");

								postTime = sdf.format(new Date());

								jsonObject.put("userName", user.getUsername());
								jsonObject.put("subjectId", newsId);
								jsonObject.put("postIp", null);
								jsonObject.put("parentId", "");

								jsonObject.put("postTime", postTime);
								jsonObject.put("postContent", text);

								jsonObject.put("add_user", user.getUsername());
								jsonObject.put("add_from", 1);
								jsonObject.put("_method", "post");

								json = jsonObject.toString();

							} catch (JSONException e) {
								e.printStackTrace();
							}

							// 验证的用户名
							String authUserName = new ConfigUtil(getResources())
									.getRestUsername();

							// 验证的密码
							String authPassword = new ConfigUtil(getResources())
									.getRestPassword();

							String requestUrl = new ConfigUtil(getResources())
									.getPreHttpUrl()
									+ getString(R.string.new_comm_upload);

							HttpUtils httpUtils = HttpUtils.getInstance();

							httpUtils
									.setOnRequestExecuted(new OnRequestExecuted() {

										@Override
										public void onRequestExecuted(
												int responseCode,
												String responseBody) {

											responseCodeRet = responseCode;

											responseBodyRet = responseBody;

										}
									});

							httpUtils.sendRequest(requestUrl, json, "POST",
									"UTF-8", authUserName, authPassword, user);

							return null;
						}

						protected void onPostExecute(Integer result) {

							switch (responseCodeRet) {
								case HttpUtils.SUCCESS:

									Toast.makeText(NewsCommentActivity.this,
											"评论发表成功!", Toast.LENGTH_SHORT).show();

									setResult(NewDetailActivity.TO_COMMENT);

									NewsCommentActivity.this.finish();
									break;

								case HttpUtils.TIMEOUT:

									DialogUtil
											.showMessageDialog(
													"评论失败,"
															+ getString(R.string.message_socktimeout),
													null, NewsCommentActivity.this);

									break;

								case HttpUtils.UNKNOWERROR:

									DialogUtil
											.showMessageDialog(
													"评论失败,"
															+ getString(R.string.message_softerror),
													null, NewsCommentActivity.this);

									break;

								default:
									DialogUtil.showMessageDialog("评论失败,发生未知错误..",
											null, NewsCommentActivity.this);

									break;

							}

						};

					}.execute();

				} else {
					DialogUtil.showMessageDialog(
							getString(R.string.error_no_network), null,
							NewsCommentActivity.this);
				}
			}
		});

		edtCommend = (EditText) findViewById(R.id.edtCommend);

		String text = preferences.getString(newsId, null);

		if (CharsetUtil.isNotNull(text)) {
			edtCommend.setText(text);
			edtCommend.requestFocus();
		}

		// edtCommend.addTextChangedListener(new TextWatcher() {
		//
		// private int preLength = 0;
		//
		// private int endLength = 0;
		//
		// private int preCursorPosition = 0;
		//
		// @Override
		// public void onTextChanged(CharSequence s, int start, int before,
		// int count) {
		// preCursorPosition -= before;
		// }
		//
		// @Override
		// public void beforeTextChanged(CharSequence s, int start, int count,
		// int after) {
		// preLength = edtCommend.length();
		// preCursorPosition = start + after;
		// }
		//
		// @Override
		// public void afterTextChanged(Editable s) {
		//
		// endLength = s.length();
		//
		// if (preLength != endLength) {
		//
		// InitApplication initApp = (InitApplication) getApplication();
		//
		// EmojiUtil emojiUtil = initApp.getEmojiUtil();
		//
		// String text = edtCommend.getText().toString().trim();
		//
		// text = emojiUtil.parseEmoji(text);
		//
		// SpannableString string = emojiUtil.getExpressionString(
		// NewsCommentActivity.this, text);
		//
		// edtCommend.setText(string);
		//
		// Selection.setSelection(edtCommend.getText(),
		// preCursorPosition);
		//
		// }
		//
		// }
		// });

		loadRightTitle();

	}

	/**
	 * 加载去主页的按钮
	 */
	public void loadRightTitle() {

		ViewGroup btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);

		View view = GoHomeUtil.createPopView(getApplicationContext(),
				new String[] { "主页" });

		// 弹出更多的菜单
		final PopupWindow pop = new PopupWindow(view,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);

		// 需要设置一下此参数，点击外边可消失
		pop.setBackgroundDrawable(new BitmapDrawable());

		// 设置点击窗口外边窗口消失
		pop.setOutsideTouchable(true);

		// 设置此参数获得焦点，否则无法点击
		pop.setFocusable(true);

		final Button btn01 = (Button) pop.getContentView().findViewWithTag(
				"btn0");

		OnClickListener menuOnClick = new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (v == btn01) {
					GoHomeUtil.goHome(getApplicationContext());
				}
			}
		};

		btn01.setOnClickListener(menuOnClick);

		btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);

		btnMeanMore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (pop.isShowing()) {
					// 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
					pop.dismiss();
				} else {
					// 显示窗口
					pop.showAsDropDown(v);
				}

			}
		});

	}

	private void doBack() {
		String text = edtCommend.getText().toString();

		if (CharsetUtil.isNotNull(text)) {

			final CustomDialog exitDialog = new CustomDialog(
					NewsCommentActivity.this);

			exitDialog.setOnCancleClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					Editor editor = preferences.edit();

					editor.putString(newsId, null);

					editor.commit();

					setResult(NewDetailActivity.TO_COMMENT);

					NewsCommentActivity.this.finish();

				}
			});

			exitDialog.setOnActionClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					Editor editor = preferences.edit();

					String text = edtCommend.getText().toString().trim();

					editor.putString(newsId, text);

					editor.commit();

					setResult(NewDetailActivity.TO_COMMENT);

					NewsCommentActivity.this.finish();

				}
			});

			exitDialog.setMessage("您的评论尚未发送,是否存储?");

			exitDialog.setCancleTxt("放弃");

			exitDialog.setActionTxt("存储");

			exitDialog.show();

		} else {
			this.finish();
		}

	}

	@Override
	public void onBackPressed() {
		doBack();
	}
}
